<template>
  <a-modal v-model:visible="visible" title="设置联系电话" width="480" unmount-on-close :mask-closable="false" :on-before-ok="onSubmit">
    <a-alert class="custom-alert">发送给订单承租人违章短信中的联系电话，建议设置违章专员</a-alert>
    <page-form :model="form" ref="formRef" layout="vertical" class="page-form" :gutter="0" :rules="rules">
      <page-form-item field="phone" label="联系电话" size="1" style="margin-bottom: 0" validate-trigger="blur">
        <i-input v-model="form.phone" style="width: 240px" />
      </page-form-item>
    </page-form>
  </a-modal>
</template>

<script setup lang="ts">
  import { ref } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { getBusinessMessageDetail, setViolationPhone } from '@/api/business/message'

  const visible = ref(false)
  const emits = defineEmits(['ok'])
  const form = ref({})
  const rules = ref({
    phone: [{ match: /^\d*$/, message: '请输入正确的联系电话' }],
  })

  const formRef = ref()
  const onSubmit = (done: Function) => {
    formRef.value.validate((error: any) => {
      if (error) {
        console.log(error)
        done(false)
      } else {
        setViolationPhone(form.value)
          .then((res: any) => {
            if (res.code == 200) {
              Message.success('操作成功')
              done(true)

              emits('ok')
            } else {
              Message.error(res.msg)
              done(false)
            }
          })
          .catch(() => {
            done(false)
          })
      }
    })
  }

  // id 业务模板id
  const open = (id: number) => {
    visible.value = true
    form.value = {}

    // 获取联系电话
    getBusinessMessageDetail({ id }).then((res: any) => {
      if (res.code == 200) {
        const result = res.result
        form.value = {
          type: result.type,
          // 后面必须加上 || ''，否则会 form 的 validate 校验 null 值会报必填
          phone: result.sendConfigJson?.phone || '',
        }
      }
    })
  }

  defineExpose({
    open,
  })
</script>

<style lang="less" scoped>
  .custom-alert {
    margin-bottom: 16px;
  }
</style>
